import moment from "moment";
import _ from "lodash";

export const SET_STATE = function (state, payload) {
    for (const p in payload) {
        const _state = state[p]
        if (Array.isArray(_state)) {
            state[p] = JSON.parse(JSON.stringify(payload[p]))
        } else if (typeof _state === 'object') {
            if (payload[p]) {
                const obj = {..._state, ...payload[p]}
                state[p] = JSON.parse(JSON.stringify(obj))
            } else {
                state[p] = JSON.parse(JSON.stringify(payload[p]))
            }
        } else {
            state[p] = JSON.parse(JSON.stringify(payload[p]))
        }
    }
}

export const formatAddress = (val, defaultValue = '') => {
    let a = ''
    if (val) {
        a += val.slice(0, 5)
         a += '...'
        a += val.slice(-5)
    } else {
        a = defaultValue
    }
    return a
}
export const formatDate = (val, format = 'YYYY-MM-DD HH:mm:ss') => {
    if (val) {
        return moment.unix(val).format(format)
    }
    return '-'
}

export function useLoading(e = 100, delay = 1000) {
    const node = document.getElementById('loading');
    const content = document.getElementById('loading-content');
    if (e) {
        node.style.display = "flex"
        content.style.width = e + '%'
    } else {
        content.style.width = '100%'
        const timer = setTimeout(() => {
            node.style.display = "none"
            clearTimeout(timer)
        }, delay|| 500)
    }
}

export function formatAmount(val = 0, u = 2) {
    return _.floor(val, u).toFixed(u)
}

